package com.imooc.news_manager_project.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.news_manager_project.common.Result;
import com.imooc.news_manager_project.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RedisInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头当中的令牌值
        String token = request.getHeader("token");
        if (redisUtil.get(token) != null) {
            // 如果不为空，表示用户已进行登录认证，刷新token有效时间为30分钟
            redisUtil.expire(token, 1800);
            return true;
        } else {
            Result result = new Result(101, "token,请重新登录获取token值");
            String json = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
    }

}
